package com.yinhai.message.core.adapterManager;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;

import com.yinhai.core.common.api.util.ValidateUtil;
import com.yinhai.message.api.exception.TMException;
import com.yinhai.message.api.vo.TMMessageVo;

/**
 * 消息适配器管理器
 * @author maxp 2017年3月30日11:45:38
 */
public class AdapterManager implements ApplicationEventPublisherAware{

	private static final Logger LOGGER = LoggerFactory.getLogger(AdapterManager.class);

	/**
	 * 所有的消息的适配器，配置在spring-adapter.xml中
	 */
	private List<IAdapter> adapterLists;

	private ApplicationEventPublisher applicationEventPublisher;

	public void setAdapterLists(List<IAdapter> adapterLists) {
		this.adapterLists = adapterLists;
	}

	public void  adapter(TMMessageVo amqVo){
		if(ValidateUtil.isNotEmpty(adapterLists)){
			List<String> messageTypes = amqVo.getMessage().getMessageTypes();
			if(ValidateUtil.isNotEmpty(messageTypes)){
				for(String type:messageTypes){
					for(IAdapter adapter : adapterLists){
						if(adapter.getSenderType().equals(type)){
							LOGGER.debug("发布事件===============================================");
							applicationEventPublisher.publishEvent(adapter.getEven(amqVo));
						}
					}
				}
			}else{
				LOGGER.error("消息的发送类型为空");
				throw new TMException("消息的发送类型为空");
			}
		}
	}

	@Override
	public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
		this.applicationEventPublisher = applicationEventPublisher;
	}
}
